
//  FirstPageViewController.m
//  FruitVIP
//
//  Created by 孙艳玲 on 15/5/21.
//  Copyright (c) 2015年 孙艳玲. All rights reserved.
//

#import "FirstPageViewController.h"


#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface FirstPageViewController ()

@property (nonatomic,strong) UIBezierPath *path;

@end

@implementation FirstPageViewController

{
    CALayer     *layer;
    UILabel     *_cntLabel;
    NSInteger    _cnt;
    UIImageView *_imageView;
    UIButton    *_btn;
}


- (void)viewDidAppear:(BOOL)animated

{
    self.tabBarController.tabBar.hidden = YES;
 self.navigationController.navigationBarHidden = YES;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;    //让rootView禁止滑动
        
    }
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
 self.navigationController.navigationBarHidden = YES;
    self.navigationItem.hidesBackButton = YES;
    self.tabBarController.selectedViewController = [self.tabBarController.viewControllers objectAtIndex:0];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
  //初始化
    _cnt = 0;
    
    self.array = [NSMutableArray arrayWithObjects:@"one.jpg",@"two.jpg", @"there.jpg", @"four.jpg", @"five.jpg", @"six.jpg", nil];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *naView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    naView.backgroundColor = [UIColor colorWithRed:255.0/255.0 green:205.0 / 255.0 blue:0 / 255.0 alpha:1];
    [self.view addSubview:naView];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 15                                                                                                                                                                                         , 60,40)];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    UIImage *image = [UIImage imageNamed:@"daohanglan.png"];
    imageView.image = image;
    [naView addSubview:imageView];

    
    self.myTopView = [[TopView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 44)];
    self.myTopView.myDetailDelegate = self;
    self.myTopView.myFruitDelegate = self;
    [self.view addSubview:self.myTopView];
    
    self.firstTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44 + 64 , SCREEN_WIDTH, SCREEN_HEIGHT - 49 - 44 - 64)];
//    self.firstTableView.backgroundColor = [UIColor colorWithRed:158.0 / 255.0 green:147.0 / 255.0 blue:131.0 / 255.0 alpha:1];
    self.firstTableView.delegate = self;
    self.firstTableView.dataSource = self;
    //取消分割线
    self.firstTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.firstTableView];

    
    
    
    //苹果推荐的使用的一个标准的瀑布流类
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    //集合视图
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * 0.37) collectionViewLayout:flowLayout];
    flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH * 0.37);
    //设置华东方向为左右滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //设置item上左下右的边距大小
//        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0,0);
    self.collectionView.backgroundColor = [UIColor whiteColor];
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    self.collectionView.pagingEnabled = YES;
    //指定代理人
    self.collectionView.delegate= self;
    self.collectionView.dataSource = self;
//    [self.view addSubview:self.collectionView];
    
#warning 重点  注册cell  如果是自定义cell,这里必须要用自定义cell的类注册
    [self.collectionView registerClass:[PlaceCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];

    

    
   //页面小点点
    self.myPageVC = [[UIPageControl alloc] initWithFrame:CGRectMake(2 * SCREEN_WIDTH / 5, SCREEN_WIDTH * 0.37 - 20, SCREEN_WIDTH / 5, 20)];
//    [self.view addSubview:self.myPageVC];
    self.myPageVC.numberOfPages = 5;
//    self.myPageVC.currentPage = 1 ;
    self.myPageVC.pageIndicatorTintColor = [UIColor whiteColor];
    //当前颜色
    self.myPageVC.currentPageIndicatorTintColor = [UIColor colorWithRed:255.0/255.0 green:206.0 / 255.0 blue:0 / 255.0 alpha:1]; 
    [self.myPageVC addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventValueChanged];

  //定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(scrollAction) userInfo:nil repeats:YES];
    
    
    
    
    
#warning 重点  注册cell  如果是自定义cell,这里必须要用自定义cell的类注册
    [self.collectionView registerClass:[PlaceCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
   
   
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, self.firstTableView.frame.origin.y + self.firstTableView.frame.size.height, SCREEN_WIDTH, 49)];
    footView.backgroundColor = [UIColor colorWithRed:15.0/255.0 green:17.0/255.0 blue:30.0/255.0 alpha:1];;
    [self.view addSubview:footView];
    
    
    UIButton *firstButton = [UIButton buttonWithType:UIButtonTypeCustom];
    firstButton.frame = CGRectMake(40, 0, 40, 40);
    [firstButton setImage:[UIImage imageNamed:@"shouye_high.png"] forState:UIControlStateNormal];
    [firstButton addTarget:self action:@selector(firstButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.tabBarController.selectedViewController = [self.tabBarController.viewControllers objectAtIndex:0];
    [footView addSubview:firstButton];
    
    UIButton *secondButton = [UIButton buttonWithType:UIButtonTypeCustom];
    secondButton.frame = CGRectMake(firstButton.frame.origin.x + firstButton.frame.size.width + 60, firstButton.frame.origin.y, 40, 40);
    [secondButton setImage:[UIImage imageNamed:@"car.png"] forState:UIControlStateNormal];
    [secondButton addTarget:self action:@selector(secondButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:secondButton];
    
    // label数字 显示购物车的个数
    UIColor *customColor  = [UIColor colorWithRed:237/255.0 green:20/255.0 blue:91/255.0 alpha:1.0f];
    _cntLabel = [[UILabel alloc] initWithFrame:CGRectMake(secondButton.frame.origin.x + secondButton.frame.size.width - 8, 5, 20, 20)];
    _cntLabel.textColor = [UIColor whiteColor];
    _cntLabel.textAlignment = NSTextAlignmentCenter;
    _cntLabel.font = [UIFont boldSystemFontOfSize:13];
    _cntLabel.backgroundColor = [UIColor whiteColor];
    _cntLabel.layer.cornerRadius = CGRectGetHeight(_cntLabel.bounds)/2;
    _cntLabel.layer.masksToBounds = YES;
    _cntLabel.backgroundColor = [UIColor whiteColor];
//    _cntLabel.layer.borderWidth = 1.0f;
//    _cntLabel.layer.borderColor = customColor.CGColor
    _cntLabel.backgroundColor = customColor;
    [footView addSubview:_cntLabel];
    if (_cnt == 0) {
        _cntLabel.hidden = YES;
    }
    
    //设置动画
    self.path = [UIBezierPath bezierPath]; //UIBezierPath动画的基类
    [_path moveToPoint:CGPointMake(50, _cntLabel.frame.origin.y)];//设置动画的起点和终点
    [_path addQuadCurveToPoint:CGPointMake(150, 300) controlPoint:CGPointMake(150, _cntLabel.frame.origin.y)];
    
    
    UIButton *thirdButton = [UIButton buttonWithType:UIButtonTypeCustom];
    thirdButton.frame = CGRectMake(secondButton.frame.origin.x + secondButton.frame.size.width + 60, secondButton.frame.origin.y, 40, 40);
    [thirdButton setImage:[UIImage imageNamed:@"me.png"] forState:UIControlStateNormal];
    [thirdButton addTarget:self action:@selector(thirdButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:thirdButton];

    
}

- (void)firstButtonAction
{
    
    //      self.tabBarController.selectedViewController = [self.tabBarController.viewControllers objectAtIndex:0];
    
    self.tabBarController.tabBar.hidden = YES;
}
- (void)secondButtonAction
{
    self.tabBarController.selectedViewController = [self.tabBarController.viewControllers objectAtIndex:1];
}
- (void)thirdButtonAction
{
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.hidesBackButton = YES;
    MyselfViewController *myVC = [[MyselfViewController alloc] init];
    [self.navigationController pushViewController:myVC animated:NO];
    
}


//小点点根据页面的滑动而滚动
-(void)changeValue:(UIPageControl *)page
{
    NSLog(@"aaaaaa %ld", page.currentPage);
    [self.collectionView setContentOffset:CGPointMake(SCREEN_WIDTH * page.currentPage, 0) animated:YES];
}


- (void)scrollAction
{
    self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x + self.view.frame.size.width, 0);
    
    
    if (self.collectionView.contentOffset.x == 0) {
        self.collectionView.contentOffset = CGPointMake(self.view.frame.size.width * 6, 0);
        
    }else if (self.collectionView.contentOffset.x == self.view.frame.size.width * 5){
        self.collectionView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
       
    }
    
}


//判断偏移量
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
             if (self.collectionView.contentOffset.x == self.view.frame.size.width * 6) {
            
            self.myPageVC.currentPage = 5;
            
        }
        if (self.collectionView.contentOffset.x == self.view.frame.size.width * 5) {
            
            self.myPageVC.currentPage = 1;
            
        }
        for (NSInteger i = 1; i < 6; i++) {
            if (self.collectionView.contentOffset.x == self.view.frame.size.width * i) {
                self.myPageVC.currentPage = (self.collectionView.contentOffset.x / self.collectionView.frame.size.width -1);
            }
        }

}
//无限滚动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.collectionView.contentOffset.x >= self.collectionView.frame.size.width * 6) {
        [self.collectionView setContentOffset:CGPointMake(self.collectionView.frame.size.width, 0) animated:NO ];
    }
    if (self.collectionView.contentOffset.x <= 0) {
        [self.collectionView setContentOffset:CGPointMake(self.collectionView.frame.size.width * 5, 0) animated:NO];
    }
   
}

- (void)detailPage
{
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)detailAddress
{
    AddressViewController *detailVC = [[AddressViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    self.navigationItem.hidesBackButton = YES;
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = YES;

}

- (void)allFruit
{
    NSLog(@"分类信息");
//    self.firstTableView.contentOffset = CGPointMake(0, SCREEN_WIDTH * 0.39 + SCREEN_WIDTH * 0.37 * 2);
    SortViewController *sortVC = [[SortViewController alloc] init];
    [self.navigationController pushViewController:sortVC animated:YES];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
}


//必须实现的两个协议方法
//设置item个数

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
       return 7;
}
//显示item内容的方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //直接从重用池里取
    //参数1.重用标示符
    //参数2.cell的位置
    PlaceCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
   
    return cell;
  }



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    if (section == 1) {
        return 1;
    }
    if (section == 2) {
        return 1;
    }
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 1001) {
        return SCREEN_WIDTH * 0.37;
    }
    if (tableView.tag == 1002 || tableView.tag == 1003) {
        return 2 * SCREEN_WIDTH/3 + 10;
    }
    return SCREEN_WIDTH/3;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
    
        NSString *cellIndetifier = [NSString stringWithFormat:@"cell%ld", indexPath.section];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndetifier];
        tableView.tag = 1001;
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndetifier];
            cell.backgroundColor = [UIColor colorWithRed:158.0 / 255.0 green:147.0 / 255.0 blue:131.0 / 255.0 alpha:1];
            //            cell.backgroundColor = [UIColor redColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell addSubview:self.collectionView];
            [cell addSubview:self.myPageVC];
        }
   
        return cell;
    }
    if (indexPath.section == 1) {
         NSString *cellFirstInder = [NSString stringWithFormat:@"cellFirst%ld", indexPath.section];
        FirstTableViewCell *cellFirst = [tableView dequeueReusableCellWithIdentifier:cellFirstInder];
        tableView.tag = 1002;
        if (cellFirst == nil) {
            cellFirst = [[FirstTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellFirstInder];
//            cellFirst.textLabel.text = @"dd";
            cellFirst.goodsDelegate = self;
            cellFirst.firstDelegate = self;
        }
        return cellFirst;

    }
    if (indexPath.section == 2) {
        NSString *cellSecondInter = [NSString stringWithFormat:@"cellSecond%ld", indexPath.section];
        SecondTableViewCell *cellSecond = [tableView dequeueReusableCellWithIdentifier:cellSecondInter];
        tableView.tag = 1003;
        if (cellSecond == nil) {
            cellSecond = [[SecondTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellSecondInter];
            cellSecond.secondViewCarDelegate = self;
            cellSecond.secondViewImageViewDelegat = self;

        }
        return cellSecond;
    }
    else
    {
        static NSString *cellThirdInder = @"cellThird";
        ThirdTableViewCell *cellThird = [tableView dequeueReusableCellWithIdentifier:cellThirdInder];
        tableView.tag = 1004;
        if (cellThird == nil) {
            cellThird = [[ThirdTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellThirdInder];
            cellThird.thirdViewCarDelegate = self;
            cellThird.thirdViewImageDelegate = self;
        }
        return cellThird;
    }
    
   }

//购物车页面协议
- (void)goodsCar:(UIButton *)button
{
    if (!layer) {
//        button.enabled = NO;
        layer = [CALayer layer];
        layer.contents = (__bridge id)[UIImage imageNamed:@"six.jpg"].CGImage;
        layer.contentsGravity = kCAGravityResizeAspectFill;
        layer.bounds = CGRectMake(0, 0, 50, 50);
        [layer setCornerRadius:CGRectGetHeight([layer bounds]) / 2];
        layer.masksToBounds = YES;
        layer.position =CGPointMake(50, 150);
        [self.view.layer addSublayer:layer];
    }
    [self groupAnimation];

    NSLog(@"dd");
}

-(void)groupAnimation
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = _path.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    CABasicAnimation *expandAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    expandAnimation.duration = 0.5f;
    expandAnimation.fromValue = [NSNumber numberWithFloat:1];
    expandAnimation.toValue = [NSNumber numberWithFloat:2.0f];
    expandAnimation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    
    CABasicAnimation *narrowAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    narrowAnimation.beginTime = 0.5;
    narrowAnimation.fromValue = [NSNumber numberWithFloat:2.0f];
    narrowAnimation.duration = 1.5f;
    narrowAnimation.toValue = [NSNumber numberWithFloat:0.5f];
    
    narrowAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    CAAnimationGroup *groups = [CAAnimationGroup animation];
    groups.animations = @[animation,expandAnimation,narrowAnimation];
    groups.duration = 2.0f;
    groups.removedOnCompletion=NO;
    groups.fillMode=kCAFillModeForwards;
    groups.delegate = self;
    [layer addAnimation:groups forKey:@"group"];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
   
    //    [anim def];
    if (anim == [layer animationForKey:@"group"]) {
//        button.enabled = YES;
        [layer removeFromSuperlayer];
        layer = nil;
        _cnt++;
        if (_cnt) {
            _cntLabel.hidden = NO;
        }
        CATransition *animation = [CATransition animation];
        animation.duration = 0.25f;
        _cntLabel.text = [NSString stringWithFormat:@"%ld",_cnt];
        ShoppingViewController *shopVC = [[ShoppingViewController alloc] init];
        shopVC.goodsCount = _cnt;
        NSLog(@" shopVC.goodsCount =bbb %ld", shopVC.goodsCount );
        [_cntLabel.layer addAnimation:animation forKey:nil];
     CABasicAnimation *shakeAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
        shakeAnimation.duration = 0.25f;
        shakeAnimation.fromValue = [NSNumber numberWithFloat:-5];
        shakeAnimation.toValue = [NSNumber numberWithFloat:5];
        shakeAnimation.autoreverses = YES;
        [_imageView.layer addAnimation:shakeAnimation forKey:nil];
    }
}

- (void)secondViewCar
{
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜您成功加入购物车"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//    [alert show];
    if (!layer) {
        //        button.enabled = NO;
        layer = [CALayer layer];
        layer.contents = (__bridge id)[UIImage imageNamed:@"six.jpg"].CGImage;
        layer.contentsGravity = kCAGravityResizeAspectFill;
        layer.bounds = CGRectMake(0, 0, 50, 50);
        [layer setCornerRadius:CGRectGetHeight([layer bounds]) / 2];
        layer.masksToBounds = YES;
        layer.position =CGPointMake(50, 150);
        [self.view.layer addSublayer:layer];
    }
    [self groupAnimation];

}

- (void)thirdViewCar
{
    if (!layer) {
        //        button.enabled = NO;
        layer = [CALayer layer];
        layer.contents = (__bridge id)[UIImage imageNamed:@"six.jpg"].CGImage;
        layer.contentsGravity = kCAGravityResizeAspectFill;
        layer.bounds = CGRectMake(0, 0, 50, 50);
        [layer setCornerRadius:CGRectGetHeight([layer bounds]) / 2];
        layer.masksToBounds = YES;
        layer.position =CGPointMake(50, 150);
        [self.view.layer addSublayer:layer];
    }
    [self groupAnimation];

    
}
//详情页面协议
- (void)firstImage
{
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    
}
- (void)DetailImage
{
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    
    
}
- (void)thirdViewImage
{
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
